package XMl;

import org.dom4j.Document;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.Scanner;

public class xpath {
    public static void main(String[] args) throws Exception {
        Scanner input=new Scanner(System.in);
        File file = new File("C:\\Users\\董\\IdeaProjects\\JAVA76\\高级特性\\src\\XMl\\products.xml");
//        1：读取products.xml中的商品信息，输出
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(file);
        Element rootElement = read.getRootElement();//获取根元素对象（根标签）
        List<Element> product = rootElement.elements();
        for (Element o:product){
            String text = o.elementText("itemno")+"\t"+o.elementText("name")+"\t"+o.elementText("price")+"\t"+o.elementText("stockcount")+"\t"+o.elementText("unit");
            System.out.println(text);
        }

//        2：查找商品信息：根据输入的商品号，输出对应的商品信息。
        System.out.print("输入商品号:");
        String a=input.next();
        for (Element o:product) {

            if (o.elementText("itemno").equals(a)){
                String text = o.elementText("itemno")+"\t"+o.elementText("name")+"\t"+o.elementText("price")+"\t"+o.elementText("stockcount")+"\t"+o.elementText("unit");
                System.out.println(text);
            }
        }
//        3：修改products.xml，输入商品编号（itemno）和数量，修改对应商品的数量（stockcount）；没有找到商品号，给出提示。
        System.out.print("输入商品号:");
        String b=input.next();
        System.out.print("输入修改的数量:");
        String c=input.next();

        for (Element o:product) {
            if (o.elementText("itemno").equals(b)){
                o.element("stockcount").setText(c);
                String text = o.elementText("itemno")+"\t"+o.elementText("name")+"\t"+o.elementText("price")+"\t"+o.elementText("stockcount")+"\t"+o.elementText("unit");
                System.out.println(text);
                OutputFormat format = OutputFormat.createPrettyPrint();
                //设置编码格式
                format.setEncoding("UTF-8");
                    XMLWriter writer = new XMLWriter(new FileWriter(file),format);
                    //写入数据
                    writer.write(read);
                    writer.close();
            }
        }

        for (Element o:product){
            String text = o.elementText("itemno")+"\t"+o.elementText("name")+"\t"+o.elementText("price")+"\t"+o.elementText("stockcount")+"\t"+o.elementText("unit");
            System.out.println(text);
        }
    }
}
